﻿#include "../../interface/ISmoothTransform.h"

namespace swui
{
	void ISmoothTransform::_smooth_transform_mouse_event(ctlMouseEvent* me)
	{
		if(!isSmoothTransformEnabled()) return;
		if(me->eventType == ctlMouseEventType::leftDown)
		{
			ctlSmoothTransform* trans = nullptr;
			if(style_cast<ctlStyleGradient*>(_styleBase))
				trans = &style_cast<ctlStyleGradient*>(_styleBase)->smooth;
			else if(style_cast<ctlStyleSolid*>(_styleBase))
				trans = &style_cast<ctlStyleSolid*>(_styleBase)->smooth;
			else return;
			trans->enterLeave = ctlSmoothTransform::minValue;
		}
		if(me->eventType == ctlMouseEventType::enter
			|| me->eventType == ctlMouseEventType::leave
			|| me->eventType == ctlMouseEventType::leftUp)
		{
			//已经有计时器在工作
			if(_smooth_transform_timer_id != 0)
				return;
			//没有计时器在工作
			auto func = [this] ()->bool {
				if(isMouseDown()) 
				{
					_smooth_transform_timer_id = 0;
					return false;
				}
				ctlSmoothTransform* trans = nullptr;
				if(style_cast<ctlStyleGradient*>(_styleBase))
					trans = &style_cast<ctlStyleGradient*>(_styleBase)->smooth;
				else if(style_cast<ctlStyleSolid*>(_styleBase))
					trans = &style_cast<ctlStyleSolid*>(_styleBase)->smooth;
				else { _smooth_transform_timer_id = 0; return false; }
				float stepLen = static_cast<float>(getSmoothTransformStepTime())
					/ static_cast<float>(getSmoothTransformTime()) *
					(ctlSmoothTransform::maxValue - ctlSmoothTransform::minValue);
				if(isMouseStay())
				{
					trans->enterLeave -= static_cast<int>(stepLen);
					if(trans->enterLeave <= ctlSmoothTransform::minValue)
					{
						trans->enterLeave = ctlSmoothTransform::minValue;
						_smooth_transform_timer_id = 0;
						redraw();
						return false;
					}
				} else {
					trans->enterLeave += static_cast<int>(stepLen);
					if(trans->enterLeave >= ctlSmoothTransform::maxValue)
					{
						trans->enterLeave = ctlSmoothTransform::maxValue;
						_smooth_transform_timer_id = 0;
						redraw();
						return false;
					}
				}
				redraw();
				return true;
			};
			func();
			_smooth_transform_timer_id = _eventTrans.setTimer(
				getSmoothTransformStepTime(), func);
		}
	}
}